//
//  AlarmHelper.swift
//  YOKO
//
//  Created by Zoe_G on 16/5/30.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import UIKit
import RealmSwift

class AlarmHelper: NSObject {

	let realm: Realm

	override init () {
        let alarmRealm = try! Realm()
		self.realm = alarmRealm
	}

	func add(alarm: Alarm) {

		try! self.realm.write {
			self.realm.add(alarm, update: false)
		}

	}

	func findAll() -> Results<Alarm> {
		return self.realm.objects(Alarm)
	}

	func findByEventId(id: String) -> Results<Alarm>? {
		let predicate = NSPredicate(format: "eventId == %@", id)

		return self.realm.objects(Alarm).filter(predicate)
	}

	func findByBegindateAndEnddate(begin: NSDate, end: NSDate) -> Results<Alarm>? {
		let predicate = NSPredicate(format: "fireDate<=%@ AND fireDate>=%@ ", end, begin)
		// 默认升序
		return self.realm.objects(Alarm).filter(predicate).sorted("fireDate")
	}
    
    func findByFiredate(date: NSDate) -> Results<Alarm>? {
        return self.findByBegindateAndEnddate(date, end: date)
    }

	func findByBeforedate(before: NSDate) -> Results<Alarm>? {
		let predicate = NSPredicate(format: "fireDate<=%@ ", before)
		// 默认升序
		return self.realm.objects(Alarm).filter(predicate).sorted("fireDate")
	}

    func deleteAlarm(alarm: Alarm) {
		if let results = findByEventId(alarm.eventId) {

			try! realm.write {
				realm.delete(results)
			}
		}
	}

	func deleteByEventId(id: String) {
		if let results = findByEventId(id) {
			try! realm.write {
				realm.delete(results)
			}
		}

	}
    
}
